<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar" style="display: flex; justify-content: center; margin-bottom: 20px;">
      <!-- 分类选择 -->
      <el-select v-model="selectedCategory" placeholder="选择分类" class="category-select" style="width: 20%; max-width: 150px; margin-right: 10px;">
        <el-option label="全部" value="全部"></el-option>
        <el-option label="传统音乐类" value="传统音乐类"></el-option>
        <el-option label="新国风流行类" value="新国风流行类"></el-option>
        <el-option label="戏曲融合类" value="戏曲融合类"></el-option>
        <el-option label="主题文化类" value="主题文化类"></el-option>
        <el-option label="地域特色类" value="地域特色类"></el-option>
      </el-select>

      <!-- 查询输入框 -->
      <el-input 
        placeholder="请输入乐谱名称" 
        v-model="queryStr" 
        class="input-with-select" 
        style="width: 50%; max-width: 400px; margin-right: 10px;">
      </el-input>

      <!-- 查询按钮 -->
      <el-button 
        class="button" 
        @click="queryInfo" 
        style="margin-top: 6px; background-color: transparent; border: 1px solid #dcdfe6; color: #333;">
        查询
      </el-button>
    </div>

    <!-- 内容展示 -->
    <el-row gutter="30">
      <el-col v-for="(notation, index) in filterNotation" :key="index" :span="6" class="notation-item">
        <el-card class="notation-out">
            <img :src="'http://localhost:8080/images/upload/' + notation.cover_image" alt="乐谱封面"
              class="notation-cover" @click="goToNotationDetail(notation)"/>
            <div class="notation-info">
              <h4>{{ notation.name }}</h4>
              <p>{{ notation.type }}</p>
            </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <el-pagination
  :current-page.sync="currentPage"
  :page-size="pageSize"
  :total="totalItems"
  layout="prev, pager, next"
  @current-change="handlePageChange"
/>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 12,
      totalItems: 20,
      selectedCategory: '全部', // 选择的分类
      filterNotation: [], // 过滤后的乐谱列表
      notationList: [], // 用户收藏的所有乐谱数据
      queryStr: '', // 查询条件
      userId: sessionStorage.getItem("user_id"), // 获取用户ID
    };
  },
  created() {
    this.fetchCollectionData(); // 初始化获取用户的收藏数据
  },
  methods: {
    goToNotationDetail(item) {
    // 调用后端接口增加浏览量
    this.incrementViewCount(item.notation_id).then(() => {
      // 浏览量增加后，再进行页面跳转
      sessionStorage.setItem('notation_id', item.notation_id);
      this.$router.push({ path: '/notation/' + item.notation_id });
    }).catch(error => {
      console.error('Failed to increment view count:', error);
      // 即使增加浏览量失败，也进行页面跳转
      sessionStorage.setItem('notation_id', item.notation_id);
      this.$router.push({ path: '/notation/' + item.notation_id });
    });
  },
  incrementViewCount(notationId) {
    return axios.post(`/v1/notation/View/${notationId}`).then(response => {
      console.log('View count incremented');
      return response;
    }).catch(error => {
      console.error('Failed to increment view count:', error);
      throw error;
    });
  },
    handlePageChange(page) {
      this.currentPage = page;
      this.updateFilteredList();
    },
    fetchCollectionData() {
      // 获取用户收藏的乐谱数据
      axios
        .get(`/v1/${this.userId}`) // 返回该用户的收藏列表
        .then((response) => {
          this.notationList = response.data;
          this.filterNotation = this.notationList; // 默认显示全部数据
        })
        .catch((error) => {
          console.error('获取收藏乐谱数据失败：', error);
        });
    },

    queryInfo() {
      // 搜索和筛选
      let filteredList = this.notationList;

      // 如果选择了分类，先根据分类过滤
      if (this.selectedCategory !== '全部') {
        filteredList = filteredList.filter(item => item.type === this.selectedCategory);
      }

      // 根据搜索关键词过滤
      if (this.queryStr.trim().length > 0) {
        filteredList = filteredList.filter(item => item.name.includes(this.queryStr.trim()));
      }

      // 更新显示的过滤后的数据
      this.filterNotation = filteredList;
    },
  },
};
</script>
<style>
.notation-out {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background: #fff;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
border-radius: 10px;
overflow: hidden;
}

.notation-item {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
}

.notation-cover {
width: 100%;
height: 200px; /* 固定图片的高度，确保占据卡片的上方区域 */
object-fit: cover; /* 确保图片填充区域，不变形 */
}

.notation-info {
padding: 10px;
flex-grow: 1; /* 让文本区域填充剩余空间 */
text-align: center;
}

.notation-info h4 {
font-size: 16px;
font-weight: 600;
color: #333;
margin-top: 10px;
}

.notation-info p {
font-size: 14px;
color: #777;
}

.search-bar {
margin-bottom: 20px;
text-align: center;
}
</style>
